﻿// <snippetJQueryRESTDataOperations.Functions>
/// <reference path="jquery1.4.1vsdoc.js" />

//GetGlobalContext function exists in ClientGlobalContext.js.aspx so the
//host HTML page must have a reference to ClientGlobalContext.js.aspx.
var context = GetGlobalContext();


//Retrieve the server url, which differs on-premise from on-line and 
//shouldn't be hard-coded.
// var serverUrl = context.getServerUrl();
var serverUrl = "/" + context.getOrgUniqueName();

//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var ORGSVC_ENDPOINT = "/XRMServices/2011/Organization.svc/web";

///<summary>
///Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
///     Create a new record
///</summary>
/// <param name="entityObject" type="Object" required="true">
///1: entity - a loose-type object representing an OData entity. any fields
///                 on this object must be camel-cased and named exactly as they 
///                 appear in entity metadata
///</param>
/// <param name="odataSetName" type="string" required="true">
///1: set -    a string representing an OData Set. OData provides uri access
///                 to any CRM entity collection. examples: AccountSet, ContactSet,
///                 OpportunitySet. 
///</param>
/// <param name="successCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon success
///                 of the ajax invocation.
///</param>
/// <param name="errorCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon error
///                 of the ajax invocation.
///</param>
function createRecordSync(entityObject, odataSetName) {

 //entityObject is required
 if (!entityObject) {
  alert("entityObject is required.");
  return;
 }
 //odataSetName is required, i.e. "AccountSet"
 if (!odataSetName) {
  alert("odataSetName is required.");
  return;
 }

 //Parse the entity object into JSON
 var jsonEntity = window.JSON.stringify(entityObject);

 //Asynchronous AJAX function to Create a CRM record using OData
 var r = $.ajax({
     type: "POST",
     async: false,
     contentType: "application/json; charset=utf-8",
     datatype: "json",
     url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
     data: jsonEntity,
     beforeSend: function (XMLHttpRequest) {
         //Specifying this header ensures that the results will be returned as JSON.             
         XMLHttpRequest.setRequestHeader("Accept", "application/json");
     }
 });

 return JSON.parse(r.responseText).d;
}


///<summary>
///Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
///     retrieve an existing record
///</summary>
/// <param name="id" type="guid" required="true">
///1: id -     the guid (primarykey) of the record to be retrieved
///</param>
/// <param name="odataSetName" type="string" required="true">
///1: set -    a string representing an OData Set. OData provides uri access
///                 to any CRM entity collection. examples: AccountSet, ContactSet,
///                 OpportunitySet. 
///</param>
/// <param name="successCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon success
///                 of the ajax invocation.
///</param>
/// <param name="errorCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon error
///                 of the ajax invocation.
///</param>
function retrieveRecord(id, odataSetName, successCallback, errorCallback) {
    
 //id is required
 if (!id) {
  alert("record id is required.");
  return;
 }
 //odataSetName is required, i.e. "AccountSet"
 if (!odataSetName) {
  alert("odataSetName is required.");
  return;
 }

 //Asynchronous AJAX function to Retrieve a CRM record using OData
 $.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
  beforeSend: function (XMLHttpRequest) {
   //Specifying this header ensures that the results will be returned as JSON.             
   XMLHttpRequest.setRequestHeader("Accept", "application/json");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   if (successCallback) {
    successCallback(data.d, textStatus, XmlHttpRequest);
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   if (errorCallback)
    errorCallback(XmlHttpRequest, textStatus, errorThrown);
   else
    errorHandler(XmlHttpRequest, textStatus, errorThrown);
  }
 });
}


function retrieveRecordSync(id, odataSetName) {

    //id is required
    if (!id) {
        alert("record id is required.");
        return;
    }
    //odataSetName is required, i.e. "AccountSet"
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    //Asynchronous AJAX function to Retrieve a CRM record using OData
    return JSON.parse($.ajax({
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        }
    }).responseText).d;
}

///<summary>
///Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
///     Retrieve multiple records
///</summary>
/// <param name="odataSetName" type="string" required="true">
///1: set -    a string representing an OData Set. OData provides uri access
///                 to any CRM entity collection. examples: AccountSet, ContactSet,
///                 OpportunitySet. 
///</param>
/// <param name="filter" type="string">
///1: filter - a string representing the filter that is appended to the odatasetname
///                 of the OData URI.     
///</param>
/// <param name="successCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon success
///                 of the ajax invocation.
///</param>
/// <param name="errorCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon error
///                 of the ajax invocation.
///</param>
function retrieveMultiple(odataSetName, filter, successCallback, errorCallback) {

 //odataSetName is required, i.e. "AccountSet"
 if (!odataSetName) {
  alert("odataSetName is required.");
  return;
 }

 //Build the URI
 var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName;  // + "()";

 //If a filter is supplied, append it to the OData URI
 if (filter) {
  odataUri += filter;
 }

 //Asynchronous AJAX function to Retrieve CRM records using OData
 $.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: odataUri,
  beforeSend: function (XMLHttpRequest) {
   //Specifying this header ensures that the results will be returned as JSON.             
   XMLHttpRequest.setRequestHeader("Accept", "application/json");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   if (successCallback) {
    if (data && data.d && data.d.results) {
     successCallback(data.d.results, textStatus, XmlHttpRequest);
    }
    else if (data && data.d) {
     successCallback(data.d, textStatus, XmlHttpRequest);
    }
    else {
     successCallback(data, textStatus, XmlHttpRequest);
    }
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   if (errorCallback)
    errorCallback(XmlHttpRequest, textStatus, errorThrown);
   else
    errorHandler(XmlHttpRequest, textStatus, errorThrown);
  }
 });
}


///<summary>
///Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
///     update an existing record
///</summary>
/// <param name="id" type="guid" required="true">
///1: id -     the guid (primarykey) of the record to be retrieved
///</param>
/// <param name="entityObject" type="Object" required="true">
///1: entity - a loose-type object representing an OData entity. any fields
///                 on this object must be camel-cased and named exactly as they 
///                 appear in entity metadata
///</param>
/// <param name="odataSetName" type="string" required="true">
///1: set -    a string representing an OData Set. OData provides uri access
///                 to any CRM entity collection. examples: AccountSet, ContactSet,
///                 OpportunitySet. 
///</param>
/// <param name="successCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon success
///                 of the ajax invocation.
///</param>
/// <param name="errorCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon error
///                 of the ajax invocation.
///</param>
function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback) {

 //id is required
 if (!id) {
  alert("record id is required.");
  return;
 }
 //odataSetName is required, i.e. "AccountSet"
 if (!odataSetName) {
  alert("odataSetName is required.");
  return;
 }

 //Parse the entity object into JSON
 var jsonEntity = window.JSON.stringify(entityObject);

 //Asynchronous AJAX function to Update a CRM record using OData
 $.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  data: jsonEntity,
  url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
  beforeSend: function (XMLHttpRequest) {
   //Specifying this header ensures that the results will be returned as JSON.             
   XMLHttpRequest.setRequestHeader("Accept", "application/json");

   //Specify the HTTP method MERGE to update just the changes you are submitting.             
   XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   //The MERGE does not return any data at all, so we'll add the id 
   //onto the data object so it can be leveraged in a Callback. When data 
   //is used in the callback function, the field will be named generically, "id"
   data = new Object();
   data.id = id;
   if (successCallback) {
    successCallback(data, textStatus, XmlHttpRequest);
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   if (errorCallback)
    errorCallback(XmlHttpRequest, textStatus, errorThrown);
   else
    errorHandler(XmlHttpRequest, textStatus, errorThrown);
  }
 });
}


///<summary>
///Uses jQuery's AJAX object to call the Microsoft Dynamics CRM OData endpoint to
///     delete an existing record
///</summary>
/// <param name="id" type="guid" required="true">
///1: id -     the guid (primarykey) of the record to be retrieved
///</param>
/// <param name="odataSetName" type="string" required="true">
///1: set -    a string representing an OData Set. OData provides uri access
///                 to any CRM entity collection. examples: AccountSet, ContactSet,
///                 OpportunitySet. 
///</param>
/// <param name="successCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon success
///                 of the ajax invocation.
///</param>
/// <param name="errorCallback" type="function" >
///1: callback-a function that can be supplied as a callback upon error
///                 of the ajax invocation.
///</param>
function deleteRecord(id, odataSetName, successCallback, errorCallback) {

 //id is required
 if (!id) {
  alert("record id is required.");
  return;
 }
 //odataSetName is required, i.e. "AccountSet"
 if (!odataSetName) {
  alert("odataSetName is required.");
  return;
 }

 //Asynchronous AJAX function to Delete a CRM record using OData
 $.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
  beforeSend: function (XMLHttpRequest) {
   //Specifying this header ensures that the results will be returned as JSON.                 
   XMLHttpRequest.setRequestHeader("Accept", "application/json");

   //Specify the HTTP method DELETE to perform a delete operation.                 
   XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   if (successCallback) {
    successCallback(data.d, textStatus, XmlHttpRequest);
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   if (errorCallback)
    errorCallback(XmlHttpRequest, textStatus, errorThrown);
   else
    errorHandler(XmlHttpRequest, textStatus, errorThrown);
  }
 });
}

///<summary>
///A function that will display the error results of an AJAX operation
///</summary>
function errorHandler(xmlHttpRequest, textStatus, errorThrow) {
 alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}
// </snippetJQueryRESTDataOperations.Functions>


function sendEmail(emailId) { 

    var requestMain = ""
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request i:type=\"b:SendEmailRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <c:key>EmailId</c:key>";
        requestMain += "            <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + emailId + "</c:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <c:key>IssueSend</c:key>";
        requestMain += "            <c:value i:type=\"d:boolean\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\">true</c:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <c:key>TrackingToken</c:key>";
        requestMain += "            <c:value i:type=\"d:string\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\" />";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>SendEmail</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";
        var req = new XMLHttpRequest();
        req.open("POST", serverUrl + ORGSVC_ENDPOINT, false)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        var successCallback = null;
        var errorCallback = null;
        req.send(requestMain);

        // POST http://marx:5555/RadikalPlus/XRMServices/2011/Organization.svc/web

}
